package com.ct.ecommerce.goods.config;

import cn.hutool.core.io.FileUtil;
import com.ct.ecommerce.framework.security.CustomerAccessTokenConverter;
import java.nio.charset.Charset;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * @author changtong
 * @since 2021/5/31
 */
@Configuration
@Slf4j
public class ResourceConfig extends ResourceServerConfigurerAdapter {

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        ClassPathResource resource = new ClassPathResource("publicKey.txt");
        String publicKey = null;
        try {
            publicKey = FileUtil.readString(resource.getPath(), Charset.defaultCharset());
        }catch (Exception e){
            log.error("解析错误：",e);
        }
        converter.setVerifierKey(publicKey);
        converter.setAccessTokenConverter(new CustomerAccessTokenConverter());
        return converter;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenStore(tokenStore());
    }


}
